import _kebabCase from "lodash.kebabcase";

export interface Options {
  /**
   * 检查目标系列组件
   * @param name
   * @returns
   */
  checkIsSeries: (name: string) => boolean;
  /**
   * 获取组件名称
   * @param name
   * @returns
   */
  getComponentName: (name: string) => string;
  /**
   * 组件dir
   * @param name
   * @returns
   */
  componentsDir: string;
  /**
   * 获取样式路径
   * @param name
   * @returns
   */
  getStylePath: (options: {
    name: string;
    componentName: string;
    kebabComponentName: string;
  }) => string;
  /**
   * 是否开启调试模式
   */
  debug?: boolean;
}

/**
 * 组件加载解析器
 */
export const resolver = ({
  checkIsSeries,
  getComponentName,
  getStylePath,
  componentsDir,
  debug,
}: Options) => {
  return {
    type: "component" as const,
    resolve: (name: string) => {
      debug && console.log(`接收到组件${name}`);

      if (checkIsSeries(name)) {
        const componentName = getComponentName(name);
        const stylePath = getStylePath({
          name,
          componentName,
          kebabComponentName: _kebabCase(componentName),
        });

        debug &&
          console.log(`
          ${name}
          ${componentName}
          ${stylePath}
        `);
        return {
          name: componentName,
          from: componentsDir,
          sideEffects: stylePath,
        };
      } else {
        debug && console.log(`组件${name}不是系列组件，不处理`);
        return;
      }
    },
  };
};
